<template>
  <div>
    <a-form
      ref="manaPlanFormRef"
      class="mana-plan-form"
      :label-col="{ style: { width: '105px' } }"
      :disabled="isPushed"
      :model="updatedData"
    >
      <div class="mana-plan-item-info" v-for="(item, index) in updatedData" :key="index">
        <div
          style="
            display: flex;
            place-content: center space-between;
            margin-bottom: 10px;
            border-bottom: 1px solid #e8e8e8;
          "
        >
          <a-form-item label="提醒时间" :rules="[{ required: true, message: '请输入提醒时间' }]">
            <div style="display: flex; align-items: center">
              <div style="display: flex; align-items: center">
                第
                <a-input-number
                  style="margin: 0 8px"
                  :min="1"
                  :precision="0"
                  v-model:value="item.cronCycle"
                  @change="(value) => changeTemCronCycleDebounced(item, value)"
                  :disabled="
                    item.sendTime
                      ? new Date().getTime() > new Date(item.sendTime).getTime()
                      : false || isPushed
                  "
                />
                天提醒一次
              </div>
              <a-date-picker
                :showToday="false"
                style="margin-left: 24px"
                v-model:value="item.sendTime"
                :disabled="
                  item.sendTime
                    ? new Date().getTime() > new Date(item.sendTime).getTime()
                    : false || isPushed
                "
                @change="(value) => changeTemSendTime(item, value)"
                :disabled-date="
                  (current) =>
                    !current ||
                    current < dayjs() ||
                    current <= dayjs(props.startTime) ||
                    current > dayjs(props.expiredTime)
                "
                :allowClear="false"
              />
            </div>
          </a-form-item>
          <a-button
            type="link"
            danger
            @click="removePlanItem(index)"
            :disabled="
              isPushed || item.sendTime
                ? new Date().getTime() > new Date(item.sendTime).getTime()
                : false
            "
          >
            删除
          </a-button>
        </div>
        <div>
          <a-form-item label="当前模板库">
            <div style="display: flex; align-content: center">
              <a-space :size="[0, 0]">
                <span
                  @click="changeTemplate(item, '公共模板')"
                  :class="
                    item.templateAffiliation == '公共模板'
                      ? 'template-col template-col-active'
                      : 'template-col'
                  "
                  >健康随访模板库</span
                >
                <span
                  @click="changeTemplate(item, '个人模板')"
                  :class="
                    item.templateAffiliation == '个人模板'
                      ? 'template-col template-col-active'
                      : 'template-col'
                  "
                  >个人模板库</span
                >
              </a-space>
            </div>
          </a-form-item>
          <a-form-item label="选择模板" :rules="[{ required: true, message: '选择模板' }]">
            <a-select
              v-model:value="item.templateId"
              placeholder="请选择模板"
              :options="item.templateList"
              @change="templateChange(item, $event, index)"
              showSearch
              :disabled="isPushed || new Date().getTime() > new Date(item.sendTime).getTime()"
            />
          </a-form-item>
        </div>
      </div>
      <a-button
        @click="addPlanItem"
        :icon="h(PlusOutlined)"
        type="primary"
        ghost
        v-if="!isPushed"
        class="add-plan-item"
      >
        添加
      </a-button>
    </a-form>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, h, defineEmits, watchEffect } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import store from '@/store'
import { getTemplateDetailList, TemplateAddOrUpdate } from '@/api/healthManaWorkbench/index'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { debounce } from 'lodash'

const manaPlanFormRef = ref()
const props = defineProps<{
  isPushed: boolean
  followData: any[]
  startTime: string
  expiredTime: string
}>()

const userId = ref()
const templateDataList = ref()

// 模板
const individualTemplateList = ref()
const individualOpen = ref<boolean>(false)
const individualName = ref<string>('')
const individualFormData = reactive({
  templateName: '',
  templateType: '',
  content: '',
  data: {}
})

const emit = defineEmits(['update:followData'])

const updatedData = ref<any>([])
onMounted(async () => {
  userId.value = store.userApp.userInfo.id

  templateDataList.value = await getTemplateList(null, null)

  nextTick(() => {
    updatedData.value = [...props.followData]
  })
})

watchEffect(() => {
  if (props.followData && props.followData.length > 0) {
    updatedData.value = [...props.followData]
  }
})

const changeTemCronCycleDebounced = debounce((item, value) => {
  if (value) {
    const newTime = dayjs(props.startTime).add(value, 'day')
    const lastTime = dayjs(props.expiredTime)
    if (newTime.isBefore(dayjs())) {
      item.cronCycle = item.cronCycleInit
      if (item.cronCycle) {
        item.sendTime = dayjs(props.startTime).add(item.cronCycle, 'day')
      } else {
        item.sendTime = ''
      }
      message.error('过去的时间不支持输入，请重新修改')
      return
    }

    if (newTime.isAfter(lastTime)) {
      item.cronCycle = item.cronCycleInit
      if (item.cronCycle) {
        item.sendTime = dayjs(props.startTime).add(item.cronCycle, 'day')
      } else {
        item.sendTime = ''
      }
      message.error('超过会员过期时间不支持输入，请重新修改')
      return
    }

    changeTemCronCycle(item, value)
  } else {
    item.sendTime = ''
  }
}, 1000)
// 时间天改变
const changeTemCronCycle = (data, value) => {
  data.sendTime = dayjs(props.startTime).add(value, 'day')
}

const changeTemSendTime = (data, value) => {
  const time = dayjs(value)
  data.cronCycle = time.diff(dayjs(props.startTime), 'day')
}

const removePlanItem = (index: any) => {
  updatedData.value.splice(index, 1) // 删除指定项
  updatedData.value = [...updatedData.value]
  emit('update:followData', updatedData.value)
}

// 模板切换
const changeTemplate = (data, type) => {
  if (props.isPushed || new Date().getTime() > new Date(data.sendTime).getTime()) {
    return
  } else {
    if (data.templateAffiliation == type) {
      //
    } else {
      data.templateAffiliation = type

      data.templateList = templateDataList.value.filter((tem) => {
        if (type == '个人模板') {
          return (
            tem.templateType == data.templateType &&
            tem.templateAffiliation == type &&
            tem.creator == userId.value
          )
        }
        return tem.templateType == data.templateType && tem.templateAffiliation == type
      })

      if (data.oldTemplateAffiliation != type) {
        data.templateId = data.templateList.length > 0 ? data.templateList[0].id : undefined
      } else {
        data.templateId = data.oldTemeplateId
      }

      const temData: any = data.templateList.find((tem) => {
        return tem.id == data.templateId
      })
      data.content = temData ? temData.content : ''
    }
  }
}

const addPlanItem = () => {
  updatedData.value.push({
    templateAffiliation: '公共模板',
    cronCycle: '',
    templateName: '',
    templateId: undefined,
    templateType: '健康随访',
    content: '',
    templateList: templateDataList.value.filter((tem) => {
      return tem.templateType == '健康随访' && tem.templateAffiliation == '公共模板'
    })
  })
  console.log(updatedData.value)
  emit('update:followData', updatedData.value)
}

// 选择模板切换
const templateChange = (data, e, index) => {
  // 根据选择的模板更新内容
  const selectedTemplate = data.templateList.find((tem) => tem.id == e)
  data.content = selectedTemplate ? selectedTemplate.content : ''
  data.templateId = e
  data.templateName = selectedTemplate ? selectedTemplate.templateName : ''

  updatedData.value[index] = { ...data }

  emit('update:followData', updatedData.value)
}

// 根据方案类型 模板类型获取响应的列表
const getTemplateList = async (templateType, templateAffiliation) => {
  let data: any = []
  const res = await getTemplateDetailList({
    templateType: templateType,
    templateAffiliation: templateAffiliation,
    platformId: store.userStore.platformId
  })

  res.data.map((item: any) => {
    item.label = item.templateName
    item.value = item.id
  })
  data = res.data
  return data
}
</script>
<style lang="less" scoped>
.mana-plan-item-info {
  padding: 16px 0;
  margin-bottom: 16px;
  border: 1px solid #e5e5e5;
}

.mana-plan-form .ant-form-item {
  padding-left: 24px;
  margin-bottom: 12px;
}

.mana-plan-form .sprot-form .ant-form-item {
  margin-bottom: 18px;
}

.template-col {
  padding: 6px 20px;
  cursor: pointer;
  border: 1px solid #e5e5e5;
  border-radius: 2px;
}

.template-col.template-col-active {
  color: #165dff;
  background: #e8f3ff;
  border: 1px solid #165dff;
  border-radius: 2px 0 0 2px;
}
</style>
